package com.harmontronics.hanma.paas.paas.token;

import com.harmontronics.hanma.paas.paas.utils.RequestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * @author ldb
 */
@Component("tenantUserTokenKit")
public class TenantUserTokenKit implements TokenKit,TokenRenew {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public String getTokenHashKey(Long id) {
        return TOKEN_HASH_KEY_PREFIX + id.toString();
    }

    @Override
    public String getTokenKey() {
        HttpServletRequest request = RequestUtils.getRequest();
        if (request == null) {
            return null;
        }
        String token = StringUtils.trimWhitespace(request.getHeader("Access-Token"));
        return StringUtils.isEmpty(token) ? StringUtils.trimWhitespace(request.getParameter("Access-Token")) : token;
    }

    @Override
    public Long getId() {
        return parseId(this.getTokenKey());
    }

    @Override
    public Boolean getPreview() {
        HttpServletRequest request = RequestUtils.getRequest();
        if (request == null) {
            return false;
        }

        String appPreview = StringUtils.trimWhitespace(request.getHeader("App-Preview"));
        return "true".equals(appPreview);
    }

    @Override
    public StringRedisTemplate getRedisTemplate() {
        return stringRedisTemplate;
    }

    @Override
    public TokenKit getTokenKit() {
        return this;
    }
}
